package com.bootdo.order.task;

import com.alibaba.fastjson.JSONObject;
import com.bootdo.common.utils.ExceptionUtils;
import com.bootdo.order.dao.OrderDao;
import com.bootdo.order.domain.OrderDO;
import com.bootdo.order.utils.HttpClientUtil;
import com.bootdo.order.utils.MD5SignUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

public class RequestTask implements Runnable {

    private static final Logger logger = LoggerFactory.getLogger(RequestTask.class);

    private String token;
    private OrderDO order;
    private OrderDao orderMapper;

    public RequestTask(String token, OrderDO order, OrderDao orderMapper){
        this.token = token;
        this.order = order;
        this.orderMapper = orderMapper;
    }

    @Override
    public void run() {
        //调用支付回调
        long requestTime = System.currentTimeMillis();

        Map<String, String> map = new HashMap<>();
        map.put("payType", order.getPayType() + "");
        map.put("actualMoney", order.getActualMoney() + "");
        map.put("money", order.getMoney() + "");
        map.put("billNo", order.getId());
        map.put("orderNo", order.getOrderNo());
        map.put("token", token);
        map.put("identification", order.getIdentification());
        map.put("requestTime", requestTime + "");
        Map<String, String> signMap = new HashMap<>();
        signMap.put("requestTime", requestTime + "");
        signMap.put("token", map.get("token"));
        signMap.put("identification", map.get("identification"));
        signMap.put("payType", map.get("payType"));
        String sign = MD5SignUtil.sign(signMap);
        logger.info("<============点击确认收款回调请求地址============>" + order.getNotifyUrl());
        logger.info("<============点击确认收款回调请求参数============>" + JSONObject.toJSONString(map));
        try {
            String rJson = HttpClientUtil.httpPost(order.getNotifyUrl(), map, sign);
            if ("success".equalsIgnoreCase(rJson)){
                //回调成功
                int res = orderMapper.updateCallBackStatus(order);
                logger.info("<============调用线程回调成功============>：" + order.getOrderNo() + "，支付类型："+order.getPayType() + "，更新状态："+res);
            }
            orderMapper.updateCallBackNumber(order);
        } catch (Exception e) {
            logger.error("<============调用线程回调失败============>：" + order.getOrderNo() + "，支付类型："+order.getPayType()+"，失败原型"+ ExceptionUtils.getStackTraceAsString(e));
        } finally {
            orderMapper = null;
            Thread.currentThread().interrupt();
        }
    }
}
